package cn.stu.cms.service.impl;


import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.StrUtil;
import cn.stu.cms.dto.SetTeamDto;
import cn.stu.cms.mapper.EmployeesMapper;
import cn.stu.cms.mapper.TeamsMapper;
import cn.stu.cms.pojo.Employees;
import cn.stu.cms.pojo.Teams;
import cn.stu.cms.service.EmployeesService;
import cn.stu.cms.util.MinioTool;
import cn.stu.cms.util.R;
import cn.stu.cms.util.UserHolder;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.regex.Pattern;

import static cn.stu.cms.common.CommonConstants.*;

/**
 * (Employees)表服务实现类
 *
 * @author gh
 * @since 2023-07-21 15:18:43
 */
@Service
@AllArgsConstructor
public class EmployeesServiceImpl extends ServiceImpl<EmployeesMapper, Employees> implements EmployeesService {

    private TeamsMapper teamsMapper;


    private MinioTool minioTool;

    private AsyncMethod asyncMethod;


    /**
     * 设置团队
     *
     * @param setTeamDto 将团队数据设置为
     * @return {@link R}<{@link Boolean}>
     */
    @Override
    public R<Boolean> setTeam(SetTeamDto setTeamDto) {
        LambdaQueryWrapper<Teams> teamQuery = new LambdaQueryWrapper<>();
        teamQuery.eq(Teams::getTeamId, setTeamDto.getTeamId());
        boolean teamExists = teamsMapper.exists(teamQuery);
        if (!teamExists) {
            return R.failed("团队" + NO_EXIST_MSG);
        }
        boolean userExists = lambdaQuery().eq(Employees::getUserId, setTeamDto.getUserId()).exists();
        if (!userExists) {
            return R.failed("用户" + NO_EXIST_MSG);
        }
        lambdaUpdate().eq(Employees::getUserId, setTeamDto.getUserId()).set(Employees::getTeamId, setTeamDto.getTeamId()).update();
        return R.ok(EDIT_OK_MSG);
    }

    @Override
    public R<Boolean> setPhone(String phone) {
        if (StrUtil.isBlank(phone)) {
            return R.failed("手机号不合法");
        }
        String telNum = "(^((13[0-9])|(14[5-8])|(15([0-3]|[5-9]))|(16[6])|(17[0|4|6|7|8])|(18[0-9])|(19[8-9]))\\d{8}$)|(^((170[0|5])|(174[0|1]))\\d{7}$)|(^(14[1|4])\\d{10}$)";
        if (!Pattern.matches(telNum, phone)) {
            return R.failed("手机号不合法");
        }
        lambdaUpdate().set(Employees::getPhone, phone)
                .eq(Employees::getUserId, UserHolder.getUser().getUserId())
                .update();
        return R.ok(EDIT_OK_MSG);
    }

    @Override
    public R<String> fileUpload(MultipartFile newImg) {
        if (newImg == null) {
            return R.failed("无文件");
        }
        //获取UUID
        String uuid = UUID.randomUUID().toString(true);
        //获取文件名
        String originalFilename = newImg.getOriginalFilename();
        //重命名文件名
        String rename;
        Long userId = UserHolder.getUser().getUserId();
        if (originalFilename != null) {
            rename = userId + PATH_SEPERATOR + uuid + originalFilename.substring(originalFilename.lastIndexOf("."));
        } else {
            return R.failed("文件名后缀获取异常！");
        }
        Boolean upload = minioTool.upload(minioTool.avatarBucketName, newImg, rename);
        if (!upload.equals(true)) {
            return R.failed("上传失败");
        }
        String url = minioTool.getFileUrl(minioTool.avatarBucketName, rename);
        Employees employee = lambdaQuery().eq(Employees::getUserId, userId).one();
        if (StrUtil.isNotBlank(employee.getUserImage())) {
            //删除旧头像
            asyncMethod.removeImage(userId, employee.getUserImage());
        }
        String fileUrl = url.substring(url.lastIndexOf(PATH_SEPERATOR)+1);
        lambdaUpdate().set(StrUtil.isNotBlank(fileUrl), Employees::getUserImage, fileUrl).eq(Employees::getUserId, userId).update();
        return R.ok("上传成功");
    }


}
